<template>
    <div>
        <input type="file" class="file" ref="file"  @change="uploadAvatar">
        <img :src="pic" alt="" class="avatar" @click="handleClick">
    </div>
</template>

<script>
import {uploadpic} from "@/api"
import {axios,baseURL} from "@/utils/axios"
export default {
    props:['userinfo'],
    data(){
        return {
            pic:require("@/assets/images/1.gif")
        }
    },
    methods:{
        handleClick(){
            this.$refs.file.click();
        },
         uploadAvatar(){
            // console.log("开始上传");
            // console.log(this.$refs.file.files[0]);
            var file = this.$refs.file.files[0]

            // 创建表单对象  
            var data = new FormData();
            data.append("avatar",file);

        //    axios({
        //        url:"/vue/uploadpic",
        //        method:"POST",
        //        data:data
        //    }).then(res=>{
        //        console.log(res)
        //        if(res.data.type){
                   
        //            this.pic = res.data.avatar.replace(/public/,baseURL)
        //        }
        //    })

           uploadpic(data)
           .then(res=>{
               if(res.type){
                   this.pic = res.avatar.replace(/public/,baseURL);  // 图片地址优化
               }
           })

        }
    },
    mounted(){
        // 判断是否上传过头像 
        if(this.userinfo){
            if(this.userinfo.avatar){
                this.pic = this.userinfo.avatar.replace(/public/,baseURL)
            }else{
                this.pic = require("@/assets/images/1.gif")
            }
        }else{
            this.pic = require("@/assets/images/1.gif")
        }
    },
}
</script>






<style lang="scss" scoped>
.avatar{
    width:45px;
    height:45px;
    border-radius: 50%;
    cursor: pointer;
}
.file{
    display: none;
}
</style>